<template>
    <div>
        <el-table
            :data="data"
            border
            style="width: 100%;"
            :height="height || '100%'"
            :row-style="{ whiteSpace: 'nowrap' }"
            :header-row-style="{ whiteSpace: 'nowrap' }"
            :header-cell-style="headerCellStyle"
            @sort-change="sortChange"
            :default-sort = "defaultSort">
                <template v-for="snapshot in tableColumns">
                
                    <el-table-column v-if="!snapshot.type" 
                        :key="snapshot.prop" 
                        :width="isAutoWidth ? 'auto' :snapshot.width"
                        :prop="snapshot.prop"
                        :formatter="snapshot.formatter"
                        :sortable="snapshot.sort || null"
                        :align="snapshot.align" :label="snapshot.label" :fixed="snapshot.fixed"
                    >
                        <template slot-scope="scope">
                            <span style="display:none;" class="stype" v-if="scope.row['stype']"></span>
                            <!-- <div v-if="typeof snapshot.formatter == 'function'"
                                v-html="snapshot.formatter(scope.row, snapshot, scope.row[snapshot.prop] ?? '')"></div> -->
                            
                            <div v-if="snapshot.prop == 'spend'" class="cost">
                                {{ scope.row[snapshot.prop] }}
                            </div>
                            <div v-else-if="snapshot.ishide">
                                <div @click="copyText(scope.row[snapshot.prop], snapshot.prop)" v-if="snapshot.prop == 'account_name' && scope.row['account_name'] && scope.row['account_name'] != '-----'">
                                    <div class="name">{{ scope.row[snapshot.prop] }}</div>
                                    <div class="yue">余额:{{ scope.row['spend_cap'] }}</div>
                                </div>
                                <span v-else class="hideSpan" @click="copyText(scope.row[snapshot.prop], snapshot.prop)">{{ scope.row[snapshot.prop] }}</span>
                            </div>
                            <div v-else-if="snapshot.prop =='ads_status'">
                                <div class="block">
                                    <template v-if="scope.row['account_status'] == 2">
                                        <span>封禁</span>
                                    </template>
                                    <template v-else>
                                        <el-switch
                                            @change="onChangeAdStatus(scope.row)"
                                            v-if="(scope.row[snapshot.prop] != '-----') && (scope.row[snapshot.prop] != 'deleted') 
                                                && (scope.row[snapshot.prop] != 'refusal')"
                                            v-model="scope.row['isOpenAd']"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949">
                                        </el-switch> 
                                        <span style="color:red;" v-if="(scope.row[snapshot.prop] == 'deleted') || (scope.row[snapshot.prop] == 'refusal')">
                                            {{ adsStatus[scope.row[snapshot.prop]] || '-----' }}
                                        </span>
                                        <span v-else>{{ adsStatus[scope.row[snapshot.prop]] || '-----' }}</span>
                                    </template>
                                </div>
                                <div class="block" v-if="scope.row['mark_tag']">
                                    <span style="color:#409EFF">{{ scope.row['mark_tag'] }}</span>
                                </div>
                            </div>
                            <div v-else-if="snapshot.prop == 'daily_budget'">
                                <div class="block" v-if="scope.row.ad_set_id">
                                    {{ scope.row[snapshot.prop] }}
                                    <el-link @click="onChangeDailyBudget(scope.row)" title="修改日预算" style="margin-left: 5px;" icon="el-icon-edit"></el-link>
                                </div>
                                <div class="block" v-else>
                                    ---
                                </div>
                            </div>
                            <div v-else-if="snapshot.prop == 'preview_url'">
                                <span class="pImg" v-if="(scope.row[snapshot.prop] != '-----')" @click="onPrewImg(scope.row)">
                                    <img :src="scope.row[snapshot.prop]" alt="" v-if="(scope.row['type']=='image')" />
                                    <template v-if="(scope.row['type']=='video')">  
                                        <i class="el-icon-caret-right play" @click="onPrewImg(scope.row)"></i>
                                        <video :src="scope.row[snapshot.prop]" style="width:100%;height: 100%;" ></video>
                                    </template>
                                </span>
                                <span v-else>
                                    {{scope.row[snapshot.prop]}}
                                </span>
                            </div>
                            <div v-else v-html="snapshot.formatter ?? scope.row[snapshot.prop]"></div>

                        </template>
                    </el-table-column>
                </template>
            </el-table>
            <browse-view ref="BrowseViewRef"></browse-view>
            <el-dialog
            title="修改预算"
            :visible.sync="dialogVisible"
            width="300px"
            :close-on-click-modal="false"
            :before-close="handleClose">
            <el-input type="text" placeholder="请输入预算" @input="onInput" v-model="day_buget"></el-input>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onOKChangeBudget">确 定</el-button>
            </span>
            </el-dialog>
        </div>
</template>

<script>
import {change_adgroup_status, changeBudget} from "@/api/reportData"
import BrowseView from "@/components/BrowseView.vue"
export default {
    name: 'adReportTable',
    props: {
        // 表格数据
        data: {
            type: Array,
            default: () => [],
        },
         // 列数据
         columns: {
            type: Array,
            default: () => [],
         },
        //  默认排序值
        defaultSort: {
            type: Object,
            default: () => {}
        },
        // 高度
        tableHeight: {
            type: Number,
            default: 500
        }
    },
    components: {BrowseView},
    data() {
        return {
            tableColumns: [],
            adsStatus: {
                PAUSED: '暂停',
                ACTIVE: '开启',
                deleted: '已删除',
                refusal: '已拒审'
            },
            height: '',
            copyTextObj: {
                account_name: '广告账号名字',
                adset_name: '广告组名字',
                ad_name: '广告名字'
            },
            isAutoWidth: false,
            dialogVisible: false,
            day_buget: ''

        }
    },
    created() {
        // this.tableColumns = this.columns.map( (item) => {
        //     console.log(['selection'].includes(item?.type) && null === item?.formatter)
        //     // if (!['selection'].includes(item?.type) && null === item?.formatter) {
        //         item.formatter = (row, attr, val) => [null, undefined, ''].includes(val) ? '----' : val;
        //     // }
        //     console.log(item)
        //     return item.checked;
        // });
        this.tableColumns = this.columns.filter( (item) => item.checked)
        this.changeWidthAuto();
    },
    computed: {
        headerCellStyle() {
            return {
                background:'#ececf1',
                fontWeight: 700,
                color: '#000000',
                borderColor: '#dfdfdf',
            }
        },
    },
    methods: {
        sortChange({ prop, order }){
            // column, 
            console.log(prop, order); // 应该打印出列的 prop 和排序顺序 
            let sort_value = order === 'descending' ? 'desc' : 'asc';
            this.$emit('on-sort', {sort_key: prop, sort_value: sort_value})
        },
        onChangeAdStatus(item) {
            let ads_status = item.isOpenAd ? 'ACTIVE' : 'PAUSED';
            let content = item.isOpenAd ? '是否要暂停广告？' : '是否要暂停广告？';

            this.$confirm(content, "提示", {
                type: "warning"
            }).then(() => {
                item.ads_status = ads_status;
                this.on_change_adgroup_status(item)
            }).catch(e => {
                console.log('yahsdf ',e)
                item.isOpenAd = !item.isOpenAd;
            });
        },
        onChangeDailyBudget(item) {
            if(!item) return;
            // let ad_set_id = item.ad_set_id;
            this.item = item;
            this.dialogVisible = true;
            // this.ad_set_id = ad_set_id;
        },
        handleClose() {
            this.dialogVisible = false;
        },
        on_change_adgroup_status(item) {
            let send_data = {
                account_id: item.account_id,
                ad_id: item.ad_id,
                status: item.ads_status
            }
            // console.log(send_data)
            // console.log(change_adgroup_status)
            let ads_status_content = item.isOpenAd ? '广告开启成功' : '广告开启失败';
            change_adgroup_status(send_data).then(ret => {
                if(ret && ret.code === 0) {
                    this.$message.success(ret.msg || ads_status_content)
                } else if(ret && ret.code == 1){
                    this.$message.warning(ret.msg || '广告已经删除')
                    item.ads_status = 'deleted';
                } else if(ret && ret.code == 2){
                    this.$message.warning(ret.msg || '广告已经拒审')
                    item.ads_status = 'refusal';
                }else {
                    item.isOpenAd = !item.isOpenAd;
                    item.ads_status = (item.isOpenAd ? 'ACTIVE' : 'PAUSED'); //改回来
                    this.$message.error(ret.msg || ads_status_content)
                }
            })
        },
        copyText(text, filed) {
            this.$copyText(text).then(() => {
                this.$message.success(`【${this.copyTextObj[filed]}】复制成功~`)
            })
        },
        onPrewImg(item) {
            if(!item) return;
            let type = (item.type == 'image') ? 1 : 2;
            let url = item?.url || item.preview_url;
            this.$refs.BrowseViewRef && this.$refs.BrowseViewRef.onShow({type: type, url: url})
        },
        changeWidthAuto() {
            // console.log('tableColumns',this.tableColumns.length)
            if(this.tableColumns.length < 5) {
                this.isAutoWidth = true
            }else {
                this.isAutoWidth = false
            }
        },
        onInput(value) {
            let reg = /[^\d]/g;
            value = value.replace(reg, '')
            this.day_buget = value;
        },
        onOKChangeBudget() {
            
            if(!this.day_buget) {
                this.$message.warning("请输入预算");
                return;
            }
            let {ad_set_id, account_id, ad_id} = this.item;
            if(!ad_set_id||!account_id|| !ad_id) {
                this.$message.warning("请选择要修改的广告组");
                return;
            }
            // account_id = 932491665354397;
            // ad_id = 120211981078220764;
            // ad_set_id = 120211981068210764;

            let send_data = {
                daily_budget: +this.day_buget, 
                ad_set_id: ad_set_id,
                account_id: account_id,
                ad_id: ad_id,
            }
            changeBudget(send_data).then(ret => {
                if(ret && ret.code === 0) {
                    this.$message.success("预算修改成功~");
                    this.item = '';
                    this.day_buget = '';
                    this.dialogVisible = false;
                }
                else {
                    this.$message.warning(ret.msg || "修改日预算失败~")
                }
            })

        }
    },
    watch: {
        tableHeight: {
            handler(nv) {
                console.log('tableHeight',nv)
                this.height = nv;
                this.$forceUpdate();

            },
            immediate: true,
        },
        columns: {
            handler(columns) {
                this.tableColumns = columns.filter( (item) => item.checked)
                // this.$forceUpdate();
                this.changeWidthAuto();
            },
            deep: true,
        }
    }
}
</script>

<style lang="scss" scoped>
.name{
    line-height: 18px;
    margin-top: 3px;
}
.yue{
    color: red;
    font-weight: bold;
}
.cost{
    color: orange;
}
.hideSpan{
    white-space: nowrap;
    overflow: hidden;
    max-width: 100px;
    text-overflow: ellipsis;
    display: inline-block;
}
.pImg{
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    img{
        max-width: 100%;
        max-height: 100%;
    }
}
</style>